<?php

namespace app\stores\controller\miniapp\goods;

use app\BaseController;

use app\beautiful\model\goods\GoodsGroupModel;
use app\beautiful\model\goods\GoodsOtherSkuDetailModel;
use app\beautiful\model\order\OrderGoodsModel;
use app\stores\logic\order\OrderLogic;

use app\beautiful\model\mall\FlashSaleGoodsModel;

use app\beautiful\model\mall\FlashSaleGoodsSkuModel;

use app\beautiful\model\mall\GoodsModel;

use app\beautiful\model\logs\GoodsViewsModel;

use app\stores\model\order\GoodsOrderModel;
use think\facade\Db;



class FlashSale extends BaseController{

    public function getFlashSaleGoodsList()

    {

        $today= date("y-m-d",$this->request->time());

        $where=[

            ['status','=',1],

            ['quota','>',0],

            ['is_delete','=',0],

            ['start_time','<=',$today],

            ['end_time','>=',$today],

        ];

        //获取可用的商品id集合

        $goods_where=[

            ['status','=',1],

            ['is_delete','=',0],

            ['is_open_yu','=',0],

        ];

        $goods_ids=GoodsModel::where($goods_where)->column('goods_id') ?? [];

        $where[]=['goods_id','in',$goods_ids];



        $order=['is_tui'=>'desc','fictitious_take_count'=>'desc','flash_sale_price'=>'asc'];

        $datas=FlashSaleGoodsModel::with(['goods'=>function($query){

            $query->field('goods_id,name,original_price,cover_img,total_value,type');

        }])->where($where)

            ->order($order)

            ->field('shop_id,flash_sale_goods_id,goods_id,flash_sale_price,fictitious_take_count,quota,end_time,take_count,limit_num_type')

            ->limit($this->request->limit)

            ->page($this->request->page)

            ->select()

            ->append(['flash_sale_djs'])

            ->toArray();
        foreach ($datas as $k=>$v){
            //每天限量
            if($v['limit_num_type']==1){
                //每天的订单
                $s = strtotime(date('Y-m-d').'00:00:00');
                $l = strtotime(date('Y-m-d').'23:59:59');
                $today_num = GoodsOrderModel::where(['flash_sale_goods_id'=>$v['flash_sale_goods_id'],'is_paid'=>1,'is_delete'=>0,'from_type'=>2])->whereIn('add_time',[$s,$l])->count();
                $datas[$k]['flash_sale_progress'] = (round($today_num/$v['quota'],2)*100)."%";
            }else{
                //全部库存
                $datas[$k]['flash_sale_progress'] = ($v['fictitious_take_count']+$v['quota'])<1?'100%':(round($v['fictitious_take_count']/($v['fictitious_take_count']+$v['quota']),2)*100)."%";
            }

        }
        $return['datas']=$datas;



        return $this->success($return);



    }
    public function getFlashSaleGoodsDetail()

    {

        $today= date("Y-m-d",$this->request->time());

        $flash_sale_goods_id=$this->request->param('flash_sale_goods_id/d',0);

        //保存用户门店中等级信息
        if($this->request->shopId && $this->request->memberId){
            saveMemberLevel($this->request->shopId,$this->request->memberId);
        }

        //判断秒杀

        if(null === $flash_sale_goods = FlashSaleGoodsModel::find($flash_sale_goods_id)) return $this->error('秒杀不存在');

        if($flash_sale_goods->shop_id != $this->request->shopId) return $this->error('秒杀不存在');

        if($flash_sale_goods->is_delete == 1) return $this->error('秒杀不存在');

        if($flash_sale_goods->status != 1) return $this->error('秒杀已下架');

        if($flash_sale_goods->start_time > $today) return $this->error('秒杀还未开始');

        if($flash_sale_goods->end_time < $today) return $this->error('秒杀已结束');



        //判断秒杀商品

        if(null === $goods = GoodsModel::with(['unit'=>function($query){
                $query->field('other_sku_detail_id,group_detail_name')
                    ->where(['shop_id'=>$this->request->shopId,'is_delete'=>0]);
            }])->where(['goods_id'=>$flash_sale_goods->goods_id])->find()) return $this->error('秒杀商品不存在');

        if($goods->shop_id != $this->request->shopId) return $this->error('秒杀商品不存在');

        if($goods->is_delete == 1) return $this->error('秒杀商品不存在');

        if($goods->is_open_yu == 1) return $this->error('秒杀商品不存在');

        if($goods->status != 1) return $this->error('秒杀商品已下架');



        $flash_sale_goods->append(['flash_sale_djs']);

        //判断库存
        $quota = $flash_sale_goods->quota;
        //限购
        if($flash_sale_goods->is_limit_buy){
            if($flash_sale_goods->limit_buy_type==1){
                //单个用户
                $return = GoodsOrderModel::getCount(['order_type'=>'flash_sale','shop_id'=>$this->request->shopId,'member_id'=>$this->request->memberId,'goods_id'=>$flash_sale_goods->flash_sale_goods_id,'not_status'=>[1,-1]]);
                $quota_num = $flash_sale_goods->limit_buy_num - $return['count'];
            }else{
                //单个订单
                $quota_num = $flash_sale_goods->limit_buy_num;
            }
            if($quota>$quota_num) $quota = $quota_num;
        }
        //判断限量
        if($flash_sale_goods->is_limit_num){
            if($flash_sale_goods->limit_num_type==1){
                //每天限量
                $start_time = strtotime(date("Y-m-d",time()));
                $end_time = $start_time+60*60*24;
                $return = GoodsOrderModel::getCount(['order_type'=>'flash_sale','shop_id'=>$this->request->shopId,'goods_id'=>$flash_sale_goods->flash_sale_goods_id,'not_status'=>[1,-1],'start_time'=>$start_time,'end_time'=>$end_time]);
                $quota_num = $flash_sale_goods->limit_num - $return['count'];
            }else{
                //全部库存
                $quota_num = $flash_sale_goods->quota;
            }
            if($quota>$quota_num) $quota = $quota_num;
        }

        if($flash_sale_goods->is_have_sku==1){
            $where['flash_sale_goods_id'] = $flash_sale_goods_id;
            $return_sku = FlashSaleGoodsSkuModel::list($where,['fs.add_time'=>'asc']);
            $sku = $return_sku['list'];
            if($flash_sale_goods->is_limit_buy || $flash_sale_goods->is_limit_num){
                foreach ($sku as $k=>$v){
                    if($v['quota']>$quota){
                        $sku[$k]['quota'] = $quota;
                    }
                }
            }
        }



        $detail=[

            'flash_sale_goods_id'=>$flash_sale_goods_id,

            'goods'=>[

                'goods_id'=>$goods->goods_id,

                'rotation'=>$goods->rotation,

                'cover_img'=>$goods->cover_img,

                'name'=>$goods->name,

                'original_price'=>$goods->original_price,

                'goods_details'=>$goods->goods_details,

                'type'=>$goods->type,

                'unit'=>isset($goods['unit'])?$goods['unit']['group_detail_name']:null

            ],

            'flash_sale_price'=>$flash_sale_goods->flash_sale_price,

            'show_quota'=>$flash_sale_goods->quota,

            'quota'=>$quota<0?0:$quota,

            'fictitious_take_count'=>$flash_sale_goods->fictitious_take_count,

            'flash_sale_djs'=>$flash_sale_goods->flash_sale_djs,

            'is_have_sku'=>$flash_sale_goods->is_have_sku,

            'sku'=>isset($sku) ? $sku :[],

            'flash_sale_info'=>$flash_sale_goods->flash_sale_info,

            'is_limit_buy'=>$flash_sale_goods->is_limit_buy,

            'limit_buy_type'=>$flash_sale_goods->limit_buy_type,

            'limit_buy_num'=>$flash_sale_goods->limit_buy_num,

            'is_limit_num'=>$flash_sale_goods->is_limit_num,

            'limit_num_type'=>$flash_sale_goods->limit_num_type,

            'limit_num'=>$flash_sale_goods->limit_num,

            'use_type'=>$flash_sale_goods->use_type,

            'use_time_type'=>$flash_sale_goods->use_time_type,

            'use_time_num'=>$flash_sale_goods->use_time_num,

            'use_start_time'=>$flash_sale_goods->use_start_time,

            'use_end_time'=>$flash_sale_goods->use_end_time,

            'start_sales_num'=>$flash_sale_goods->start_sales_num
        ];



        $return['detail']=$detail;

        //记录秒杀对应的产品访问

        $GoodsViewsModel = new GoodsViewsModel();

        $GoodsViewsModel->save([

            'shop_id'   => $this->request->shopId,

            'goods_id'  => $goods->goods_id

        ]);

        return $this->success($return);



    }

    public function getFlashSaleSetMealDetail()

    {

        $today= date("Y-m-d",$this->request->time());

        $flash_sale_goods_id=$this->request->param('flash_sale_goods_id/d',0);

        //保存用户门店中等级信息
        if($this->request->shopId && $this->request->memberId){
            saveMemberLevel($this->request->shopId,$this->request->memberId);
        }

        //判断秒杀

        if(null === $flash_sale_goods = FlashSaleGoodsModel::find($flash_sale_goods_id)) return $this->error('秒杀不存在');

        if($flash_sale_goods->shop_id != $this->request->shopId) return $this->error('秒杀不存在');

        if($flash_sale_goods->is_delete == 1) return $this->error('秒杀不存在');

        if($flash_sale_goods->status != 1) return $this->error('秒杀已下架');

        if($flash_sale_goods->start_time > $today) return $this->error('秒杀还未开始');

        if($flash_sale_goods->end_time < $today) return $this->error('秒杀已结束');



        //判断秒杀商品

        if(null === $goods = GoodsModel::with(['unit'])->where(['goods_id'=>$flash_sale_goods->goods_id])->find()) return $this->error('秒杀商品不存在');

        if($goods->shop_id != $this->request->shopId) return $this->error('秒杀商品不存在');

        if($goods->is_delete == 1) return $this->error('秒杀商品不存在');

        if($goods->is_open_yu == 1) return $this->error('秒杀商品不存在');

        if($goods->status != 1) return $this->error('秒杀商品已下架');



        $flash_sale_goods->append(['flash_sale_djs']);

        if($flash_sale_goods->is_have_sku==1){

            $sku=FlashSaleGoodsSkuModel::where([['flash_sale_goods_id','=',$flash_sale_goods_id],['is_delete','=',0]])

                    ->field('flash_sale_goods_sku_id,name,original_price,flash_sale_price,quota')

                    ->select()->toArray() ?? [];

        }

        //套餐分组
        $goods_group = GoodsGroupModel::with(['groupDetail'=>function($query){
                $query->where(['is_delete'=>0]);
            }])->where([['goods_id','=',$flash_sale_goods->goods_id],['is_delete','=',0]])
                ->field('goods_group_id,group_name,type,num,choose_num,is_choose_same')
                ->select()->toArray() ?? [];

        $total_price = 0;
        foreach ($goods_group as $k=>$v){

            $detail_return = $this->groupDetail($v['groupDetail'],$total_price);

            $total_price += $detail_return['total_price'];

            $goods_group[$k]['groupDetail'] = $detail_return['groupDetail'];

        }



        $detail=[

            'flash_sale_goods_id'=>$flash_sale_goods_id,

            'goods'=>[

                'goods_id'=>$goods->goods_id,

                'rotation'=>$goods->rotation,

                'cover_img'=>$goods->cover_img,

                'name'=>$goods->name,

                'original_price'=>$goods->original_price,

                'total_value'=>$goods->total_value,

                'goods_details'=>$goods->goods_details,

                'type'=>$goods->type,

                'group'=>$goods_group,

                'unit'=>isset($goods['unit'])?$goods['unit']['group_detail_name']:null

            ],

            'flash_sale_price'=>$flash_sale_goods->flash_sale_price,

            'quota'=>$flash_sale_goods->quota,

            'fictitious_take_count'=>$flash_sale_goods->fictitious_take_count,

            'flash_sale_djs'=>$flash_sale_goods->flash_sale_djs,

            'is_have_sku'=>$flash_sale_goods->is_have_sku,

            'sku'=>isset($sku) ? $sku :[],

            'flash_sale_info'=>$flash_sale_goods->flash_sale_info,

        ];



        $return['detail']=$detail;

        //记录秒杀对应的产品访问

        $GoodsViewsModel = new GoodsViewsModel();

        $GoodsViewsModel->save([

            'shop_id'   => $this->request->shopId,

            'goods_id'  => $goods->goods_id

        ]);

        return $this->success($return);



    }

    protected function groupDetail($groupDetail,$total_price){
        foreach ($groupDetail as $k=>$v){
            if($v['goods_id']){
                $goods = GoodsModel::where(['shop_id'=>$this->request->shopId,'goods_id'=>$v['goods_id'],'is_delete'=>0])->find();
                $groupDetail[$k]['goods_name'] = $goods->name;
                $groupDetail[$k]['original_price'] = $goods->original_price;

                $groupDetail[$k]['unit'] = GoodsOtherSkuDetailModel::where(['shop_id'=>$this->request->shopId,'other_sku_detail_id'=>$goods['unit_id'],'is_delete'=>0])->value('group_detail_name');

                $total_price += $goods->original_price;
            }else{
                $groupDetail[$k]['goods_name'] = $v['goods_name'];
                $groupDetail[$k]['original_price'] = $v['original_price'];
                $groupDetail[$k]['unit'] = $v['unit_name'];

            }
            $total_price += $groupDetail[$k]['original_price'];
            $groupDetail[$k]['total_goods_price'] = $v['original_price']*$v['num'];
        }
        $return['total_price'] = $total_price;
        $return['groupDetail'] = $groupDetail;
        return $return;
    }
    public function createOrder()

    {

        $logistics_type=$this->request->param('logistics_type/d');

        $receiving_name=$this->request->param('receiving_name');

        $receiving_mobile=$this->request->param('receiving_mobile');

        $receiving_address_province=$this->request->param('receiving_address_province');

        $receiving_address_city=$this->request->param('receiving_address_city');

        $receiving_address_county=$this->request->param('receiving_address_county');

        $receiving_address_info=$this->request->param('receiving_address_info');

        $total_price = $this->request->param('total_price/f',0);

        $use_integral = $this->request->param('use_integral/d',0);

        $coupon_id = $this->request->param('coupon_id/d',0);

        $goods=$this->request->param('goods/a',[]);

        $from_type = $this->request->param('from_type/d',1);

        $order_send_time = $this->request->param('order_send_time');

        $mix_pay_type = $this->request->param('mix_pay_type');

        $params=[

            'member_id'=>$this->request->memberId,

            'logistics_type'=>$logistics_type,

            'receiving_name'=>$receiving_name,

            'receiving_mobile'=>$receiving_mobile,

            'receiving_address_province'=>$receiving_address_province,

            'receiving_address_city'=>$receiving_address_city,

            'receiving_address_county'=>$receiving_address_county,

            'receiving_address_info'=>$receiving_address_info,

            'total_price'=>$total_price,

            'use_integral'=>$use_integral,

            'coupon_id'=>$coupon_id,

            'goods'=>$goods,

            'from_type'=>$from_type,

            'order_send_time'=>$order_send_time,

            'mix_pay_type'=>$mix_pay_type

        ];

        Db::startTrans();

        try{

            $order_logic = OrderLogic::init($this->request->shopId);

            $order_id=$order_logic['flash_sale']->createOrder($params);

            Db::commit();

            return $this->success(['order_id'=>$order_id]);

        } catch (\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }





    }

}

